/* Medical Calculator
Copyright (c) 2009, John Cronin
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are 
permitted provided that the following conditions are met:

- Redistributions of source code must retain the above copyright notice, this list 
  of conditions and the following disclaimer.

- Redistributions in binary form must reproduce the above copyright notice, this list
  of conditions and the following disclaimer in the documentation and/or other materials 
  provided with the distribution.

- Neither the name of the the Author nor the names of its contributors may be used to 
  endorse or promote products derived from this software without specific prior written 
  permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &AS IS& AND ANY EXPRESS 
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER 
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */

using System;
using System.Collections.Generic;

namespace MedicalCalculator
{
	/// <summary>
	/// Description of Calculator.
	/// </summary>
	public class Calculator
	{
		public static object Calculate(string calc, System.Collections.Generic.List<VariableControl> vars)
		{
			try
			{
				// tokenise the input
				string[] toks = ToToken(calc);
				// replace vars with values
				toks = ReplaceVars(toks, vars);
				
				return Parse(new tok_list(toks));
			}
			catch(Exception e)
			{
				return e.Message;
			}
		}
		
		public class tok_list
		{
			string[] toks;
			int i = 0;
			public tok_list(string[] tokens, int start)
			{ toks = tokens; i = start; }
			public tok_list(string[] tokens)
			{ toks = tokens; i = 0; }
		
			public string next_token()
			{
				if(i >= toks.Length)
					return ";";
				i++;
				return toks[i - 1];
			}
			
			public string peek_token()
			{
				if(i >= toks.Length)
					return ";";
				return toks[i];
			}
		}
		
		static object Parse(tok_list toks)
		{
			return Parse(toks, 0);
		}
		
		static object Parse(tok_list toks, int bracket_level)
		{
			List<string> new_toks = new List<string>();
			
			string next_tok;
			while((next_tok = toks.next_token()) != ";")
			{
				if(next_tok == "(")
					new_toks.Add(Convert.ToString(Parse(toks, bracket_level + 1)));
				else if(next_tok == ")")
					return ParseNoBrackets(new tok_list(new_toks.ToArray()));
				else
					new_toks.Add(next_tok);
			}
			if(bracket_level != 0)
				throw new Exception("Unmatched brackets in expression");
			return ParseNoBrackets(new tok_list(new_toks.ToArray()));
		}
		
		static object ParseNoBrackets(tok_list toks)
		{
			return ParseNoBrackets(Convert.ToDecimal(toks.next_token()), 0, toks);
		}
		
		static decimal ParseNoBrackets(decimal lhs, int min_precedence, tok_list toks)
		{
			string next_op = toks.next_token();
			while(Precedence(next_op) >= min_precedence)
			{
				decimal rhs = Convert.ToDecimal(toks.next_token());
				while(Precedence(toks.peek_token()) > Precedence(next_op))
				{
					string lookahead = toks.peek_token();
					rhs = ParseNoBrackets(rhs, Precedence(lookahead), toks);
				}
				lhs = DoCalc(lhs, rhs, next_op);
				next_op = toks.next_token();
			}
			return lhs;
		}
		
		static int Precedence(string op)
		{
			if((op == "+") || (op == "-"))
				return 1;
			else if((op == "*") || (op == "/") || (op == "%"))
				return 2;
			else if(op == "^")
				return 10;
			else if(op == ";")
				return -1;
			else
				throw new Exception();
		}
		
		static decimal DoCalc(decimal lhs, decimal rhs, string op)
		{
			if(op == "+")
				return lhs + rhs;
			else if(op == "-")
				return lhs - rhs;
			else if(op == "*")
				return lhs * rhs;
			else if(op == "/")
				return lhs / rhs;
			else if(op == "%")
				return lhs % rhs;
			else if(op == "^")
				return Convert.ToDecimal(Math.Pow(Convert.ToDouble(lhs), Convert.ToDouble(rhs)));
			else
				throw new Exception();
		}
		
		static string[] ReplaceVars(string[] toks, List<VariableControl> vars)
		{
			List<string> ret = new List<string>();
			foreach(string tok in toks)
			{
				string res = tok;
				foreach(VariableControl var in vars)
				{
					if(var.VarName == tok)
						res = var.Value.ToString();
				}
				ret.Add(res);
			}
			return ret.ToArray();
		}
		
		static string[] ToToken(string calc)
		{
			List<string> ret = new List<string>();
			string cur_str = "";
			for(int i = 0; i < calc.Length; i++)
			{
				if((calc[i] == ' ') || (calc[i] == '*') || (calc[i] == '+') || (calc[i] == '-') ||
				   (calc[i] == '/') || (calc[i] == '%') || (calc[i] == '(') || (calc[i] == ')') ||
				   (calc[i] == '^'))
				{
					if(cur_str.Length > 0)
					{
						ret.Add(cur_str);
					}
					if(calc[i] != ' ')
					{
						ret.Add(calc[i].ToString());
					}
					cur_str = "";
				}
				else
					cur_str += calc[i];
				if(i == (calc.Length - 1))
					ret.Add(cur_str);
			}
			return ret.ToArray();
		}
	}
}
